import { Cartesian3, Ellipsoid } from "cesium";
import { Rectangle } from "cesium";
import Camera from "./Camera";

const token = 'AAPK9250e700411749c9b0f45c5c54662f24eGi6gpLH6WTEpI4rw0r6VT0MBuAEWhFUpHonLTRzLQfho48WPf4vBRkm0QFyErIP'
// const baseUrl = 'https://ibasemaps-api.arcgis.com/arcgis/rest/services/World_Imagery/MapServer/tile'
const baseUrl = ' https://t0.tianditu.gov.cn/cia_w/wmts?tk=1415bf6128045d22d06a89146a6074d7&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles'
export default class Tile {
    minLon: number;
    maxLon: number;
    minLat: number;
    maxLat: number;
    private tileX: number;
    private tileY: number;
    private tileZ: number;
    tileUrl: string;
    positions: number[];
    private _textureData: ImageBitmap | undefined
    center: number[];
    private _rectangle: Rectangle;
    constructor(tileX: number, tileY: number, tileZ: number) {
        this.tileX = tileX;
        this.tileY = tileY;
        this.tileZ = tileZ;
        this._textureData = undefined;
        // this.tileUrl = `${baseUrl}/${tileZ}/${tileY}/${tileX}?token=${token}`;
        this.tileUrl = `https://t0.tianditu.gov.cn/vec_w/wmts?tk=1415bf6128045d22d06a89146a6074d7&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&TILEMATRIX=${tileZ}&TILEROW=${tileY}&TILECOL=${tileX}&FORMAT=tiles`;
        this.initTexture();
        const n = Math.pow(2, tileZ);
        let minLon = tileX / n * 360 - 180;
        let maxLon = (tileX + 1) / n * 360 - 180;
        let maxLat = this.radToDeg(Math.atan(Math.sinh(Math.PI * (1 - 2 * tileY / n))));
        let minLat = this.radToDeg(Math.atan(Math.sinh(Math.PI * (1 - 2 * (tileY + 1) / n))));
        this.minLon = minLon;
        this.maxLon = maxLon;
        this.minLat = minLat;
        this.maxLat = maxLat;
        this._rectangle = Rectangle.fromDegrees(minLon, minLat, maxLon, maxLat);
        this.center = [(this.minLon + this.maxLon) / 2, (this.minLat + this.maxLat) / 2]
        // console.time('createTile');
        this.positions = this.createWGS84TilePositions();
        // console.timeEnd('createTile');
    }

    public get rectangle(): Rectangle {
        return this._rectangle;
    }
    public get westnorthChild(): Tile {
        return new Tile(this.tileX * 2, this.tileY * 2, this.tileZ + 1);
    }

    public get eastnorthChild(): Tile {
        return new Tile(this.tileX * 2 + 1, this.tileY * 2, this.tileZ + 1);
    }
    public get westsouthChild(): Tile {
        return new Tile(this.tileX * 2, this.tileY * 2 + 1, this.tileZ + 1);
    }

    public get eastsouthChild(): Tile {
        return new Tile(this.tileX * 2 + 1, this.tileY * 2 + 1, this.tileZ + 1);
    }
    private radToDeg(rad: number): number {
        return rad * 180 / Math.PI;
    }

    private async initTexture() {
        let response = await fetch(this.tileUrl, {
        });
        let Blobdata = await response.blob();
        this._textureData = await createImageBitmap(Blobdata);
    }


    public get Size(): number {
        return
    }

    public get texture(): ImageBitmap | undefined {
        return this._textureData;
    }
    /**
     * @description: 前面是经度，后面是纬度
     */

    /**
     * distance
     */
    public distance(cameraPosition: Cartesian3) {
        const cartesian = Cartesian3.fromDegrees(this.center[0], this.center[1], 0);
        const x = cameraPosition.x - cartesian.x;
        const y = cameraPosition.y - cartesian.y;
        const z = cameraPosition.z - cartesian.z;
        return Math.sqrt(x * x + y * y + z * z);
    }

    private createWGS84TilePositions() {
        const vertices = [];
        const a = Ellipsoid.WGS84.radii.x; // 长半轴
        const b = Ellipsoid.WGS84.radii.z; // 短半轴
        //划分为99*199个间隔，划分为100*200个点
        let latStep = (this.maxLat - this.minLat) / 99;
        let lonStep = (this.maxLon - this.minLon) / 199;
        let lat = this.maxLat;
        let lon = this.minLon;
        for (let i = 0; i < 100; i = i + 1) {
            // 计算机的小数的加减运算是一门学问，好好学学
            //0.0和1.0这种可以用二进制精确表示的小数加减运算，是精确的
            lat = this.maxLat - i * latStep;
            if (i === 99) {
                // console.log(this.minLat, lat);
            }
            const sinTheta = Math.sin(lat / 180 * Math.PI);
            const cosTheta = Math.cos(lat / 180 * Math.PI);
            for (let j = 0; j < 200; j++) {
                lon = this.minLon + j * lonStep;
                // if(j===199){
                //     console.log(this.maxLon,lon);
                // }
                lon = this.minLon + j * lonStep;
                if (j === 199) {
                    // console.log(this.maxLon, lon);
                }
                const sinPhi = Math.sin(lon / 180 * Math.PI);
                const cosPhi = Math.cos(lon / 180 * Math.PI);
                const x = a * cosTheta * cosPhi;
                const y = a * cosTheta * sinPhi;
                const z = b * sinTheta;
                vertices.push(x, y, z);
            }
        }
        // console.log(vertices.length/3);
        // console.log(vertices.length / 3);
        return vertices;
    }
    //计算屏幕空间误差,切片的屏幕空间误差和切片的z值与相机的距离成反比
    // public getSse(camera: Camera): number {
    //     return -this.distance(camera._position) * this.tileZ;
    // }
}